package com.emm.yixun.website.service.ao.DataService;

import com.alibaba.fastjson.JSON;
import com.emm.yixun.common.model.Merchant;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.PmoLogDto;
import com.emm.yixun.common.model.dto.ResponseOrg;
import com.emm.yixun.common.model.enums.ActRemarkEnum;
import com.emm.yixun.common.model.enums.ActivityAddressEnum;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.utils.DateStyle;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.common.utils.HttpUtil;
import com.emm.yixun.system.service.MerchantServiceFacade;
import com.emm.yixun.system.service.PmoLogServiceFacade;
import com.emm.yixun.system.service.UserServiceFacade;
import com.emm.yixun.website.constant.PmoConfig;
import com.emm.yixun.website.service.call.CallCustomerServiceImp;
import com.emm.yixun.website.utils.Arithmetic;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service("oaSendHttpMessageService")
public class OaSendHttpMessageServiceImp implements OaSendHttpMessageService {

	protected Logger logger = LoggerFactory.getLogger(CallCustomerServiceImp.class);

	@Autowired
	private PmoConfig pmoConfig;

	@Autowired
	private MerchantServiceFacade merchantServiceFacade;

	@Autowired
	private UserServiceFacade userServiceFacade;

	@Autowired
	private PmoLogServiceFacade pmoLogServiceFacade;

	@Override
	public ResponseOrg sendHaveMessage(Task task, ProcessInstance processInstance, User user, ActRemarkEnum act,
			String processName) throws Exception {
		ResponseOrg responseOrg = new ResponseOrg();
		if (sendVaild(user)) { // 商户是否已经开通了方法消息
			Map<String, String> map = commonAttribute(task, processInstance, processName);
			Arithmetic.getKey(pmoConfig.getOaSysCode());
			String[] pcList = new String[] { task.getFormKey(), processInstance.getBusinessKey(), task.getId(),
					Arithmetic.getEncString(user.getId().toString()) };
			// pcurl
			map.put("pcurl", getActUrl(pmoConfig.getActivityPc(), pcList));
			String[] params = new String[] { processInstance.getBusinessKey(), task.getExecutionId(),
					user.getId().toString(), task.getId() };
			map.put("appurl", getActUrl(ActivityAddressEnum.getByName(processName).getActivityAppUrl(), params));
			map.put("isremark", act.getNo());
			map.put("viewtype", "1");
			map.put("creator", user.getUserAccount());
			map.put("createdatetime", DateUtils.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
			map.put("receiver", user.getUserAccount());
			map.put("receivedatetime", DateUtils.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
			String result = HttpUtil.doPost(pmoConfig.getActivityUrl(), map, "utf-8");
			PmoLogDto pmoLogDto = new PmoLogDto();
			pmoLogDto.setMerchantId(user.getMerchantId());
			pmoLogDto.setDirection("2");
			pmoLogDto.setStatus("1");
			pmoLogDto.setRequestParams(map.toString());
			pmoLogDto.setDelFlag("0");
			pmoLogDto.setInterfaceName("推送已办,结办信息");
			pmoLogDto.setReturnResult(result);

			pmoLogServiceFacade.save(pmoLogDto);
			return responseOrg;
		}
		return null;
	}

	@Override
	public ResponseOrg sendWaitMessage(Task task, ProcessInstance processInstance, User user, Long nextUserId,
			String nextTaskId, String processName) throws Exception {
		ResponseOrg responseOrg = new ResponseOrg();
		String[] pcList = null;
		if (sendVaild(user)) {
			Map<String, String> map = commonAttribute(task, processInstance, processName);
			if (nextUserId != null) {
				Response<User> nextUser = userServiceFacade.findById(nextUserId);
				if (nextUser.isSuccess() && nextUser != null && nextUser.getEntity() != null) {
					map.put("receiver", nextUser.getEntity().getUserAccount());
					map.put("receivedatetime", DateUtils.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
					Arithmetic.getKey(pmoConfig.getOaSysCode());
					pcList = new String[] { task.getFormKey(), processInstance.getBusinessKey(), nextTaskId,
							Arithmetic.getEncString(nextUser.getEntity().getId().toString()) };
				}
			}
			String[] params = new String[] { processInstance.getBusinessKey(), task.getExecutionId(),
					nextUserId.toString(), nextTaskId };
			map.put("appurl", getActUrl(ActivityAddressEnum.getByName(processName).getActivityAppUrl(), params));
			map.put("pcurl", getActUrl(pmoConfig.getActivityPc(), pcList));
			map.put("isremark", ActRemarkEnum.ACT_0.getNo());
			map.put("viewtype", "0");
			map.put("createdatetime", DateUtils.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
			map.put("creator", user.getUserAccount());
			String result = HttpUtil.doPost(pmoConfig.getActivityUrl(), map, "utf-8");
			// 记录日志
			PmoLogDto pmoLogDto = new PmoLogDto();
			pmoLogDto.setMerchantId(user.getMerchantId());
			pmoLogDto.setDirection("2");
			pmoLogDto.setStatus("1");
			pmoLogDto.setRequestParams(map.toString());
			pmoLogDto.setDelFlag("0");
			pmoLogDto.setInterfaceName("推送待办信息");
			pmoLogDto.setReturnResult(result);
			pmoLogServiceFacade.save(pmoLogDto);
			return responseOrg;
		}
		return null;
	}

	/**
	 * 公共属性
	 * 
	 * @param task
	 * @param processInstance
	 * @return
	 */
	public Map<String, String> commonAttribute(Task task, ProcessInstance processInstance, String processName) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("syscode", pmoConfig.getOaSysCode()); // 异构系统标识
		map.put("flowid", task.getExecutionId()); // 流程ID
		map.put("requestname", processName); // 流程标题
		map.put("nodename", task.getName()); // 流程步骤
		map.put("workflowname", "巧房销售流程");
		return map;
	}

	public String getActUrl(String url, String[] list) {

		for (int i = 0; i < list.length; i++) {
			url = url.replace("{" + i + "}", list[i]);
		}
		return url;
	}

	public boolean sendVaild(User user) {
		Response<Merchant> merchantResponse = merchantServiceFacade.findById(user.getMerchantId());
		if (merchantResponse.isSuccess() && merchantResponse.getEntity() != null) {
			String information = merchantResponse.getEntity().getPhoneInformation();
			com.alibaba.fastjson.JSONArray jsonArray = JSON.parseArray(information);
			for (int i = 0; i < jsonArray.size(); i++) {
				com.alibaba.fastjson.JSONObject jsonObject = jsonArray.getJSONObject(i);
				String type = jsonObject.getString("type");
				String status = jsonObject.getString("status");
				if ("5".equals(type) && "1".equals(status)) {
					return true;
				}
			}
		}

		return false;
	}
}
